package com.mgy.example.utils;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.Objects;

public class LockUtil {

    public static String getLockName(String lockName, String fieldName, String[] paramNames, Class[] paramTypes, Object[] paramValues) throws Exception {
        if (StringUtils.isNotBlank(lockName)) {
            return lockName;
        } else {
            Objects.requireNonNull(paramNames, "paramNames must not be null");
            return resolveParameter(fieldName, paramNames, paramTypes, paramValues).toString();
        }
    }

    public static Object resolveParameter(String fieldName, String[] paramNames, Class[] paramTypes, Object[] paramValues) throws Exception {
        for (int i = 0; i < paramNames.length; i++) {
            String paramName = paramNames[i];
            Class paramType = paramTypes[i];
            Object paramValue = paramValues[i];
            if (ClassUtils.isPrimitiveOrWrapper(paramType)) {
                if (StringUtils.equals(paramName, fieldName)) {
                    return paramValue;
                }
            } else {
                String[] nameStr = fieldName.split("\\.");
                if (nameStr.length != 2) {
                    throw new Exception("字段名称错误：fieldName=" + fieldName);
                }
                if (!StringUtils.equals(nameStr[0], paramName)) {
                    throw new Exception("字段名称错误：fieldName=" + fieldName);
                }
                Field[] fields = paramType.getDeclaredFields();
                for (Field field : fields) {
                    if (BeanUtils.isSimpleValueType(field.getType())) {
                        if (StringUtils.equals(field.getName(), nameStr[1])) {
                            field.setAccessible(true);
                            return field.get(paramValue);
                        }
                    }
                }
                throw new Exception("没有找到对应字段");
            }
        }
        throw new Exception("没有找到对应字段");
    }


}
